//
//  PromotionsVC.swift
//  d11
//
//  Created by peale on 2018/7/31.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import MJRefresh

class PromotionsVC: BXBaseVC,UITableViewDelegate,UITableViewDataSource{
    var dataArray: [[String:Any]]?
    var showDataArray = [[String:Any]]()
    var classArray: [String]? = [String]()
    var classItem:[[String:Any]]?
    let  reuseIdentifierID : NSString = "PromotionsCell"
    var  atype: String = "0"
    lazy var noDataLabel : UILabel = {
        let noLabel = UILabel.init(frame: CGRect(x: 0, y: 100, width: self.tableView.width, height:40))
        // noLabel.center = self.tableView.center
        noLabel.text =  "暂无记录"
        noLabel.isHidden = true
        noLabel.textAlignment = .center
        noLabel.textColor = HexRGBAlpha(0x666666,1)
        noLabel.font = UIFont.systemFont(ofSize: 15)
        self.tableView.addSubview(noLabel)
        return noLabel
    }()
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 60, width: self.view.width, height:kScreenHeight-kTabBarBottom-60), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = HexRGBAlpha(0xEFF0F1, 1)
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        table.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            ToolHelper.statisticsPage(pageName: "首页-优惠页面-下拉刷新")
            self.pullToRefresh()
        })
        
        return table
    }()
    
    //刷新数据
    func pullToRefresh() -> Void {
        self.dataArray?.removeAll()
        self.getRecordList()
    }
   
    //获取数据
    func getRecordList() -> Void {
        self.noDataLabel.isHidden = true
        showLoadHUD(title: "")
        var params = [String:Any]()
        params["actypeid"] = self.atype
        let paramString = RequestHelper.convertGetParams(params as! [String : String])
        //以前正式版本的活动请求
        RequestHelper.get(atPath: "/clientsAPIs/myactivity" + "?\(paramString)", withCompletion: { data in
            let activityInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
            print("优惠活动\(activityInfoArray)")
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                self.dataArray = activityInfoArray
                self.updateData()
                //   self.tableView.reloadData()
                if self.tableView.mj_header?.isRefreshing == true{
                    self.tableView.mj_header?.endRefreshing()
                }
            }
        }, withError: { error in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if self.tableView.mj_header?.isRefreshing == true{
                    self.tableView.mj_header?.endRefreshing()
                }
            
                UIHelper.alertSimpleMessage(about: "读取失败", withDescription: "未成功读取活动信息，请稍后重试,\(getErrorString())", in: self)
            }
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ToolHelper.statisticsPage(pageName: "优惠-优惠导航-全部优惠")
        self.title = "优惠"
        
        self.view.backgroundColor = HexRGBAlpha(0xEFF0F1, 1)
        self.leftButtonActionWithImg("icon_default_back")
        if let classData = GlobalInfo.activitycategoryData {
            self.classItem = classData
            for item in classData{
                print("!!!!!\(item)")
                let name :String =  item["actypename"] as! String
                self.classArray?.append(name)
            }
            self.initTopView()
            self.view.addSubview(self.tableView)
            self.getRecordList()
        }
    }
    
    //初始化顶部
    func initTopView() -> Void {
        let segment = PinterestSegment(frame: CGRect(x: 0, y:15, width: kScreenWidth, height: 30), titles:classArray!)
        segment.style.selectedTitleColor = UIColor.white
        segment.style.normalTitleColor = UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1)
        segment.selectedBgColor = UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1)
        segment.normalBgColor = UIColor.clear
        segment.normalFrameColor = UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1)
        segment.selectedFrameColor = UIColor.clear
        segment.frameWith = CGFloat(1)
        segment.valueChange = self.actionToValueChange
        view.addSubview(segment)
        
    }
    
    //分类变化
    func actionToValueChange(tag : Int ) -> Void {
        let dict = self.classItem![tag]
        let name = dict["actypename"] as? String ?? ""
          ToolHelper.statisticsPage(pageName: "优惠-优惠导航-\(name)")
        var actypeId = dict["actypeid"] as? String ?? ""
        if(actypeId==""){
            let atype = dict["actypeid"] as? Int ?? 0
            self.atype = String(atype)
        }else{
            self.atype = actypeId
        }
        let temp = dict["actypeid"] as? String
        updateData()
        
    }
    
    //类型发生变化
    func updateData() -> Void {
        self.showDataArray.removeAll()
        if self.atype == "0" {
            self.showDataArray = self.dataArray!
        }else{
            for item in self.dataArray! {
                let actypeid = item["actypeid"] as? String
                if actypeid == self.atype{
                    self.showDataArray.append(item)
                }
            }
        }
        if self.showDataArray.count == 0 {
            self.noDataLabel.isHidden = false
        }else
        {
            self.noDataLabel.isHidden = true
        }
        self.tableView.reloadData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.showDataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //     let cell : RomotionsCell = tableView.cellForRow(at: indexPath) as! RomotionsCell
        //  print("高度:\(cell.iconImageView?.image?.size.height),宽度:\(cell.iconImageView?.image?.size.width)")
        //      return 187
        return 130
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgview = UIView.init()
        bgview.backgroundColor = UIColor.clear
        return bgview
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 15
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell :RomotionsCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? RomotionsCell
        if cell == nil {
            cell =  RomotionsCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
        }
        cell?.setData(dict: self.showDataArray[indexPath.section])
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let dict = self.showDataArray[indexPath.section]
        print("\(dict)")
        let goNext = TabMineActivityDetailViewController.instanceFromStoryboard()!
        goNext.activity = dict
        //  goNext.navigationController?.navigationBar.topItem?.title = ""
        //  goNext.navigationController?.navigationItem.backBarButtonItem?.title = ""
        goNext.activityImage = imageNamed("img_default_banner")
        goNext.activityImageHeight = 65
        //实现闭包,获取到传递的参数
        goNext.listIndex = indexPath.row
        goNext.callBackBlock { (updateTitle,index) in
            var activity = self.showDataArray[indexPath.row]
            activity["canJoin"] = "5"
            activity["actname"] = updateTitle
            self.showDataArray[indexPath.row] = activity
            self.tableView.reloadData()
        }
        self.navigationController?.pushViewController(goNext, animated: true) 
    }
    
}
